package Lib;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class UserLibrary {
		private Map<Integer, BooksItem> booksList = new TreeMap<Integer, BooksItem>();

		public int addBooks(Integer booksId) {
			boolean b = Storage.storageBooksList.containsKey(booksId);
			if (b == true) {
				BooksItem storageBooksItem = Storage.storageBooksList.get(booksId);
				if (booksList.containsKey(booksId)) {
					if (booksList.get(booksId).getCount() < storageBooksItem.getCount()) {
						BooksItem temp = booksList.get(booksId);
						temp.setCount(temp.getCount() + 1);
						return 1;
					} else
						return 0;
				} else {
					booksList.put(booksId, new BooksItem(storageBooksItem.getBook(), 1));
					return 1;
				}
			} else {
				return -1;
			}
		}

		public void showBoosList() {
			Collection<BooksItem> booksItems = booksList.values();
			Iterator<BooksItem> iterator = booksItems.iterator();

			while (iterator.hasNext()) {
				BooksItem booksItem = iterator.next();
				Books books = booksItem.getBook();
				int booksId=books.getBookId();
				int stock=Storage.storageBooksList.get(booksId).getCount();
				System.out.println(String.format("GoodsId:%-4dGoodsName:%-10sGoodCategory:%-10sGoodsCount:%d/%-4dTotalMoney:%-5.3fԪ",
						books.getBookId(),books.getBookName(),books.getBookCategory(),booksItem.getCount(),stock));
			}

		}

		
		public boolean deleteBooks(int booksId) {
			if (booksList.containsKey(booksId)) {
				booksList.remove(booksId);
				return true;
			} else
				return false;
		}

	
		public boolean clearShoppingCart() {
			booksList.clear();
			return booksList.isEmpty();
		}

		
		public int modifyBooks(int booksId, int count) {

			if (booksList.containsKey(booksId)) {
				if (count > 0 && count <= Storage.storageBooksList.get(booksId).getCount()) {
					BooksItem booksItem=booksList.get(booksId);
					booksItem.setCount(count);
					return 1;
				}
				if (count == 0) {
					deleteBooks(booksId);
					return 1;
				}
				if (count > Storage.storageBooksList.get(booksId).getCount())
					return 0;
			}
			return -1;
		}

}
